package com.guxingke.typecho4j.util;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 集合操作.
 * 
 * 进行数学的‘并集’‘交集’‘减法’运算:<br>
 * 并集：addAll.<br>
 * 交集：retainAll.<br>
 * 减法：removeAll.<br>
 * 
 * @author guxingke
 */
public class SetOptUtils {

	/**
	 * 取两数交集.
	 * 
	 * @param dest
	 *                The destination set.
	 * @param src
	 *                The source set.
	 * @return the same elements of src and dest
	 */
	public static <T> Set<T> intersect(Set<T> dest, Set<T> src) {
		Set<T> set = new HashSet<T>(src.size());
		copy(set, src);
		set.retainAll(dest);
		return set;
	}

	/**
	 * 取两数并集.
	 * 
	 * @param dest
	 *                The destination set.
	 * @param src
	 *                The source set.
	 * @return the all elements of src and dest
	 */
	public static <T> Set<T> union(Set<T> dest, Set<T> src) {
		Set<T> set = new HashSet<T>(src.size());
		copy(set, src);
		set.addAll(dest);
		return set;
	}

	/**
	 * 取两数差集(减法).
	 * 
	 * @param dest
	 *                The destination set.
	 * @param src
	 *                The source set.
	 * @return the elements in src but not exist dest
	 */
	public static <T> Set<T> diff(Set<T> dest, Set<T> src) {
		Set<T> set = new HashSet<T>(src.size());
		copy(set, src);
		set.removeAll(dest);
		return set;
	}

	/**
	 * 集合判空.
	 * 
	 * @param c
	 *                The source collection.
	 * @return true/false
	 */
	public static boolean isEmpty(Collection<?> c) {
		boolean rs = false;
		if (c == null || (c != null && c.isEmpty())) {
			rs = true;
		}
		return rs;
	}

	/**
	 * 判断两集合是否有相同的元素.
	 * 
	 * @param dest
	 *                The destination set.
	 * @param src
	 *                The source list.
	 * @return true/false
	 */
	public static <T> boolean isSameElements(Set<T> dest, Set<T> src) {
		if (isEmpty(dest) || isEmpty(src)) {
			return false;
		}

		Set<T> set = intersect(dest, src);
		if (set.size() > 0) {
			return true;
		}

		return false;
	}

	/**
	 * Copies all of the elements from src set into dest.
	 * 
	 * @param dest
	 *                The destination set.
	 * @param src
	 *                The source list.
	 */
	private static <T> void copy(Set<T> dest, Set<T> src) {
		dest.addAll(src);
	}

	public static void main(String[] args) {
		Set<String> set = new HashSet<String>();
		Set<String> set2 = new HashSet<String>();
		set2.add("010W");
		set.add("010W");
		set.add("012w");
		System.out.println(diff(set2, set));
	}

}